package com.hyw.supply.security;

import com.alibaba.fastjson.JSON;
import com.hyw.supply.model.vo.CommonResult;
import com.hyw.supply.utils.CustomToken;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;

import static com.hyw.supply.enums.ResultCodeEnum.TOKEN_INVALID;

/**
 * @Author zengzhiping
 * @BelongsPackage com.aracky.system.filter
 * @CreateTime 2022-07-15
 * @Description
 */
@Component
@Slf4j
public class SecurityFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String bearerToken = request.getHeader("Authorization");
        String token = null;
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            token = bearerToken.substring(7).trim();
        }
        //获取token
        if (StringUtils.isBlank(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        try {
            //解析token
            String accountId = CustomToken.getTokenInfo(token);
            //放入springsecurity上下文
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                    new UsernamePasswordAuthenticationToken(accountId, null, new ArrayList<>());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        } catch (Exception e) {
            log.error("token validate fail:{}", e.getMessage());
            tokenValidateRes(response);
            return;
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 设置token失效相应信息
     *
     * @param response
     * @throws IOException
     */
    private void tokenValidateRes(HttpServletResponse response) throws IOException {
        CommonResult<Object> error = CommonResult.error(TOKEN_INVALID.getCode(), "token验证失败,请重新登录");
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(JSON.toJSONString(error));
    }
}
